package l.l.w.leetcode._227BasicCalculatorII;

import java.util.Stack;

/**
 * Created by llw on 2018/5/22/0022.
 */
public class _227BasicCalculatorII {

    public int calculate(String s) {
        int num = 0, res = 0;
        Stack<Integer> operatorNum = new Stack<>();
        char c;
        char sign = '+';
        for(int i = 0; i < s.length();++i){
            c = s.charAt(i);
            if(Character.isDigit(c)){
                num = num * 10 + c - '0';
            }
            // 不是 数字且不是空格，即位操作数的时候 处理前面的操作。如果是末尾的数字的话也要直接处理
            // + 把当前 数字加到栈顶
            //- 把当前数的负数 加到栈顶
            // * 栈顶元素乘以当前值，添加到栈顶
            // / 栈顶元素除以当前值，添加到栈顶
            if((!Character.isDigit(c) && c != ' ') || i == s.length() - 1){
                switch (sign){
                    case '+': operatorNum.push(num);  break;
                    case '-': operatorNum.push(-num); break;
                    case '*': operatorNum.push(operatorNum.pop() * num); break;
                    case '/': operatorNum.push(operatorNum.pop() / num); break;
                }
                num = 0;
                sign = c;
            }
        }
        while(!operatorNum.isEmpty()){
            res += operatorNum.pop();
        }
        return res;
    }

    public static void main(String[] args) {
        String s = "1+5 + 3 * 2";
        int result = new _227BasicCalculatorII().calculate(s);
        System.out.println(result);
    }
}
